<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="教室ID" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入教室ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学校" prop="schoolId">
            <!-- <el-tree-select
            clearable
                v-model="queryParams.schoolId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择学校"
                 :render-after-expand="false"
              /> -->
            <el-select v-model="queryParams.schoolId" placeholder="请选择学校" clearable :disabled="!(userId === 1 && tenantDisabled)">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId" />
            </el-select>
          </el-form-item>
          <el-form-item label="楼栋" prop="buildName">
            <!-- <el-select v-model="queryParams.buildName" placeholder="请选择楼栋" clearable>
              <el-option
                v-for="dict in sys_common_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <el-input v-model="queryParams.buildName" placeholder="请选择楼栋" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="楼层" prop="buildFloor">
            <!-- <el-select v-model="queryParams.buildFloor" placeholder="请选择楼层" clearable>
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <el-input v-model="queryParams.buildFloor" placeholder="请选择楼层" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="教室" prop="clsName">
            <el-input v-model="queryParams.clsName" placeholder="请输入教室" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
             <el-button type="primary" @click="handleAdd" v-hasPermi="['core:room:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
       <template #header>
        <h2>教室列表</h2>
      </template>

      <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="教室ID" align="center" prop="id" v-if="true" />
        <el-table-column label="学校" align="center" prop="deptName">
          <!-- <template #default="scope">
            {{getTenantById(tenantOptions,scope.row.schoolId)}}
          </template> -->
        </el-table-column>
        <el-table-column label="楼栋" align="center" prop="buildName">
          <!-- <template #default="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.buildName"/>
          </template> -->
        </el-table-column>
        <el-table-column label="楼层" align="center" prop="buildFloor">
          <!-- <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.buildFloor"/>
          </template> -->
        </el-table-column>
        <el-table-column label="教室" align="center" prop="clsName" />
        <el-table-column label="教室前摄像头流媒体地址" align="center" prop="roomFrontRstp" min-width="200">
          </el-table-column>
        
        <el-table-column label="教室后摄像头流媒体地址" align="center" prop="roomAfterRstp"  min-width="200"/>
        <el-table-column label="走廊前摄像头流媒体地址" align="center" prop="corridorFrontRstp" min-width="200" />
        <el-table-column label="走廊后摄像头流媒体地址" align="center" prop="corridorAfterRstp" min-width="200" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
              <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-hasPermi="['core:room:edit']">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)" v-hasPermi="['core:room:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改教室管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="roomFormRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="学校" prop="schoolId" v-if="userId === 1 && tenantDisabled">
          <!-- <el-tree-select
             filterable
                 clearable
                v-model="form.schoolId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择学校"
                :render-after-expand="false"
              /> -->
          <el-select v-model="form.schoolId" placeholder="请选择学校" >
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋" prop="buildName">
          <!-- <el-select v-model="form.buildName" placeholder="请选择楼栋">
            <el-option
                v-for="dict in sys_common_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select> -->
          <el-input v-model="form.buildName" placeholder="请输入楼栋" />
        </el-form-item>
        <el-form-item label="楼层" prop="buildFloor">
          <!-- <el-select v-model="form.buildFloor" placeholder="请选择楼层">
            <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select> -->
          <el-input v-model="form.buildFloor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="教室名称" prop="clsName">
          <el-input v-model="form.clsName" placeholder="请输入教室名称" />
        </el-form-item>
        <el-form-item label="教室前摄像头流媒体地址" prop="roomFrontRstp">
          <el-input v-model="form.roomFrontRstp" placeholder="请输入教室前摄像头流媒体地址" />
        </el-form-item>
        <el-form-item label="教室后摄像头流媒体地址" prop="roomAfterRstp">
          <el-input v-model="form.roomAfterRstp" placeholder="请输入教室后摄像头流媒体地址" />
        </el-form-item>
        <el-form-item label="走廊前摄像头流媒体地址" prop="corridorFrontRstp">
          <el-input v-model="form.corridorFrontRstp" placeholder="请输入走廊前摄像头流媒体地址" />
        </el-form-item>
        <el-form-item label="走廊后摄像头流媒体地址" prop="corridorAfterRstp">
          <el-input v-model="form.corridorAfterRstp" placeholder="请输入走廊后摄像头流媒体地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Room" lang="ts">
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from '@/api/core/room';
import { RoomVO, RoomQuery, RoomForm } from '@/api/core/room/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_common_status, sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_common_status', 'sys_normal_disable'));
  import { listDept } from '@/api/system/dept'; //学校
  import { DeptVO } from '@/api/system/dept/types'; //学校
const roomList = ref<RoomVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const roomFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
import { getSubjectNameById,getTeacherNameById,getTenantById } from '@/utils/index';
import { useSchoolList, useTenantlList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();

//学校改租户数据
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

// // 学校
// interface DeptOptionsType {
//   deptId: number | string;
//   deptName: string;
//   children: DeptOptionsType[];
// }
// const deptOptions = ref<DeptOptionsType[]>([]);   //学校
const initFormData: RoomForm = {
  schoolId: undefined,
  buildName: undefined,
  buildFloor: undefined,
  clsName: undefined,
  roomFrontRstp: undefined,
  roomAfterRstp: undefined,
  corridorFrontRstp: undefined,
  corridorAfterRstp: undefined,
}
const data = reactive<PageData<RoomForm, RoomQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    schoolId: undefined,
    buildName: undefined,
    buildFloor: undefined,
    clsName: undefined,
    params: {
    }
  },
  rules: {
    schoolId: [
      { required: true, message: "学校id不能为空", trigger: "change" }
    ],
    buildName: [
      { required: true, message: "楼栋不能为空", trigger: "change" }
    ],
    buildFloor: [
      { required: true, message: "楼层不能为空", trigger: "change" }
    ],
    clsName: [
      { required: true, message: "教室名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// /** 查询学校列表 */
// const  getSchoolList = async () => {
//   const res = await listDept();
//   const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
//   if (data) {
//     deptOptions.value = data;
//   }
// }
/** 查询教室管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRoom(queryParams.value);
  roomList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  roomFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RoomVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "新增教室";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RoomVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRoom(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "编辑教室";
}

/** 提交按钮 */
const submitForm = () => {
  roomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.schoolId = tenantId;
      }

      if (form.value.id) {
        await updateRoom(form.value).finally(() =>  buttonLoading.value = false);
         proxy?.$modal.msgSuccess("编辑成功");
      } else {
        await addRoom(form.value).finally(() =>  buttonLoading.value = false);
         proxy?.$modal.msgSuccess("新增成功");
      }
     
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RoomVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除教室管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delRoom(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/room/export', {
    ...queryParams.value
  }, `room_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  console.log("====",userId.value,tenantDisabled.value)
  if(!(userId.value === 1 && tenantDisabled.value)){
    // queryParams.value.schoolId = getTenantById(tenantOptions.value,tenantId.value)
    queryParams.value.schoolId = Number(tenantId.value) ;
  }
  getList();

  // getSchoolList();
});
</script>
